/**

 @Name：layuiAdmin 公共业务
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */

layui.define(['table','element'],function(exports){
  var $ = layui.$
      , layer = layui.layer
      , table = layui.table
      , form = layui.form
      , element = layui.element;

  //公共业务的逻辑处理可以写在此处，切换任何页面都会执行
    //删除表格一条/多条数据
    var obj = {

        /**
         * 将普通list结构数据转化为
         * @param arr
         * @param parentId
         * @returns {[]}
         */
        arrayToTree:function (arr, parentId) {
            //  arr 是返回的数据  parendId 父id
            var temp = [];
            var treeArr = arr;
            treeArr.forEach((item, index) => {
                if (item.parentId == parentId) {
                    if (this.arrayToTree(treeArr, treeArr[index].id).length > 0) {

                        // 递归调用此函数
                        treeArr[index].children = this.arrayToTree(treeArr, treeArr[index].id);
                    }
                    temp.push(treeArr[index]);
                }

            });
            return temp;
         },

        /**
         * 搜索
         * @param filter
         * @param tableFilter
         */
        tableSearch: function (filter, tableFilter) {
            form.on('submit(' + filter + ')', function (data) {
                var field = data.field;
                //执行重载
                table.reload(tableFilter, {
                    where: field
                });
            });
        },

        /**
         * 更改状态
         * @param url
         * @param params  更改数据id
         * @param filter  刷新表格filter或者回调函数
         * @param title  提示标题
         */
        tableStatus: function (url, params, filter, title) {
            if (title == undefined) {
                title = '确定要更改状态么？';
            }
			
			//csrf_token
            $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
            layer.confirm(title, {icon: 3, title: '提示信息'}, function (index) {
                layer.load();
                $.post(url, params, function (data) {
                    layer.closeAll('loading');
                    if (data.code==1) {
                        layer.msg(data.msg, {icon: 6, time: 1500}, function () {
                            if (typeof filter == 'string'){
                                table.reload(filter);
                            }else {
                                filter();
                            }
                        });
                    } else {
                        layer.msg(data.msg, {icon: 2});
						$.ajaxSetup({headers: {'X-CSRF-TOKEN': data.data.token}});
                    }
                });
            });
            layer.closeAll('loading');
        },

        /**
         * 批量操作表格数据
         * @param url
         * @param data  表格数据
         * @param filter  刷新表格filter或者回调函数
         * @param title  提示标题
         * @param id  操作的主键字段名称
         */
        tableCheck: function (url, data, filter, title,id) {
            if (id == undefined) {
                id = 'id';
            }
            if (data.length === 0) {
                return layer.msg('请勾选表格数据', {icon: 5});
            }
            var params = {};
            params[id] = this.checkID(data,id);
			
			//csrf_token
            $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
            layer.confirm(title, {icon: 3, title: '提示信息'}, function (index) {
                layer.load();
                $.post(url, params, function (data) {
                    layer.closeAll('loading');
                    if (data.code==1) {
                        layer.msg(data.msg, {icon: 6, time: 1500}, function () {
                            if (typeof filter == 'string'){
                                table.reload(filter);
                            }else {
                                filter();
                            }
                        });
                    } else {
                        layer.msg(data.msg, {icon: 2});
						$.ajaxSetup({headers: {'X-CSRF-TOKEN': data.data.token}});
                    }
                });
            });
            layer.closeAll('loading');
        },

        /**
         * 表格数据删除
         * @param url  删除url
         * @param ids  删除对象/id
         * @param filter 刷新表格filter或单个删除的操作对象或者回调函数
         * @param id  对象主键id
         */
        tableDelete: function (url, ids, filter,id) {
            if (typeof filter == 'string' && ids instanceof Object) {
                if (ids.length === 0) {
                    return layer.msg('请选择数据', {icon: 5});
                }

            }

            //如果id没有定义默认id
            if (id==undefined){id = 'id';}
			
			//csrf_token
            $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
            layer.confirm('确定删除操作？', {icon: 3, title: '提示信息'}, function (index) {
                //如果是多选对象
                if (ids instanceof Object) {
                    var temp = [];
                    $.each(ids, function (key, item) {
                        temp.push(item[id]);
                    });
                    ids = temp;
                }
                $.post(url, {ids: ids}, function (data) {
                    if (data.code) {
                        layer.msg(data.msg, {icon: 6, time: 1500}, function () {
                            //是lay-filter标签新表格
                            if (typeof filter == 'function'){
                                filter();
                            }else if (typeof filter == 'string') {
                                table.reload(filter);
                            } else if (filter instanceof Object) {
                                filter.del();
                            }
                        });
                    } else {
                        layer.msg(data.msg, {icon: 2});
						$.ajaxSetup({headers: {'X-CSRF-TOKEN': data.data.token}});
                    }
                });
            });
        },


        /**
         * 全屏弹窗
         * @param url
         * @param title
         */
        fullShow: function (url, title) {
            var index = layui.layer.open({
                title: title,
                type: 2,
                content: url,
                success: function (layero, index) {
                    var body = layui.layer.getChildFrame('body', index);
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500)
                }
            });
            layui.layer.full(index);
            window.sessionStorage.setItem("index", index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(window.sessionStorage.getItem("index"));
            });
        },

        /**
         * 后台添加/编辑数据 数据
         * @param title 显示题目
         * @param add_url  添加数据url
         * @param w 宽
         * @param h 高
         * @param filter 数据提交filter
         * @param reload 表格刷新filter或者回调函数
         */
        adminShow: function (add_url, title, w, h, filter, reload) {

            //是否是编辑
            if (w == null || w == '') {
                w = 800;
            }
            if (h == null || h == '') {
                h = ($(window).height() - 50);
            }
            var w_px = /^\d+$/.test(w)?'px':'';
            var h_px = /^\d+$/.test(h)?'px':'';
            layer.open({
                type: 2
                , title: title
                , content: add_url
                , area: [w + w_px, h + h_px]
                , btn: ['确定', '取消']

                , yes: function (index, layero) {

                    var iframeWindow = window['layui-layer-iframe' + index]
                        , submit = layero.find('iframe').contents().find("#" + filter)
                        , yesBtn = $('layui-layer'+index+' .layui-layer-btn0')
						, csrf_token = layero.find('iframe').contents().find('meta[name="csrf-token"]').attr('content');

                    //设置禁止点击防止双击
                    yesBtn.attr("disabled","disabled");
                    clearTimeout(timer);
                    var timer = setTimeout(function(){
                        yesBtn.removeAttr("disabled");
                    },1000);            //1秒之后释放防止双击
                    //监听提交
                    iframeWindow.layui.form.on('submit(' + filter + ')', function (data) {
                        layer.load();
                        //获取提交的字段
                        var params = data.field;
                        var post_url = add_url.substring(0, add_url.indexOf('?'));
                        post_url = post_url==''?add_url:post_url;
						
						$.ajaxSetup({headers: {'X-CSRF-TOKEN': csrf_token}});
                        $.post(post_url, params, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 1) {
                                layer.msg(res.msg, {icon: 1}, function () {
                                    layer.close(index); //关闭弹层
                                    if (typeof reload == 'function'){
                                        reload(table);
                                    }else {
                                        table.reload(reload);
                                    }
                                });
                            } else {
                                layer.msg(res.msg, {icon: 2});
								$.ajaxSetup({headers: {'X-CSRF-TOKEN': res.data.token}});
                            }
                        });
                    });

                    submit.trigger('click');
                }
            });
        },

        /**
         * 后台添加/编辑数据 没有取消按钮的
         * @param title 显示题目
         * @param add_url  添加数据url
         * @param w 宽
         * @param h 高
         * @param filter 数据提交filter
         * @param reload 表格刷新filter或者回调函数
         */
        adminShowNotCancel: function (add_url, title, w, h, filter, reload) {

            //是否是编辑
            if (w == null || w == '') {
                w = 800;
            }
            if (h == null || h == '') {
                h = ($(window).height() - 50);
            }
            var w_px = /^\d+$/.test(w)?'px':'';
            var h_px = /^\d+$/.test(h)?'px':'';
            layer.open({
                type: 2
                ,closeBtn: 0
                , title: title
                , content: add_url
                , area: [w + w_px, h + h_px]
                , btn: ['确定']
                , yes: function (index, layero) {
                    var iframeWindow = window['layui-layer-iframe' + index]
                        , submit = layero.find('iframe').contents().find("#" + filter)
                        , yesBtn = $('layui-layer'+index+' .layui-layer-btn0')
						, csrf_token = layero.find('iframe').contents().find('meta[name="csrf-token"]').attr('content');

                    //设置禁止点击防止双击
                    yesBtn.attr("disabled","disabled");
                    clearTimeout(timer);
                    var timer = setTimeout(function(){
                        yesBtn.removeAttr("disabled");
                    },1000);            //1秒之后释放防止双击
                    //监听提交
                    iframeWindow.layui.form.on('submit(' + filter + ')', function (data) {
                        layer.load();
                        //获取提交的字段
                        var params = data.field;
                        var post_url = add_url.substring(0, add_url.indexOf('?'));
                        post_url = post_url==''?add_url:post_url;
						
						$.ajaxSetup({headers: {'X-CSRF-TOKEN': csrf_token}});
                        $.post(post_url, params, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 1) {
                                layer.msg(res.msg, {icon: 1}, function () {
                                    layer.close(index); //关闭弹层
                                    if (typeof reload == 'function'){
                                        reload(table);
                                    }else {
                                        table.reload(reload);
                                    }
                                });
                            } else {
                                layer.msg(res.msg, {icon: 2});
								$.ajaxSetup({headers: {'X-CSRF-TOKEN': res.data.token}});
                            }
                        });
                    });

                    submit.trigger('click');
                }
            });
        },

        //选中table的id
        checkID:function(data,id){
            var temp = [];
            $.each(data, function (key, item) {
                temp.push(item[id]);
            });
            return temp;
        },

        //选中的id转化为字符串逗号隔开
        checkIdToString:function(data,id){
            var temp = '';
            $.each(data, function (key, item) {
                temp += temp!=''?','+item[id]:item[id];
            });
            return temp;
        },

        /**
         * 后台添加/编辑数据 数据自定义弹窗
         * @param title 显示题目
         * @param add_url  添加数据url
         * @param w 宽
         * @param h 高
         */
        alertShow: function (add_url, title, w, h) {

            //是否是编辑
            if (w == null || w == '') {
                w = 800;
            }
            if (h == null || h == '') {
                h = ($(window).height() - 50);
            }
            var w_px = /^\d+$/.test(w)?'px':'';
            var h_px = /^\d+$/.test(h)?'px':'';

            layer.open({
                type: 2
                , title: title
                , content: add_url
                , area: [w + w_px, h + h_px]
            });
        },

        /**
         * 后台弹框理由
         * @param url
         * @param params  更改数据id
         * @param filter  刷新表格filter
         * @param title  提示标题
         * @param formType  输入框类型
         */
        alertPrompt: function (url, params, filter, title,formType) {
            if (formType == undefined) {
                formType = 2;
            }
			
			//csrf_token
            $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
            layer.prompt({title: title, formType: 2}, function(text, index){
                params = $.extend(params,{content:text});
                $.post(url, params, function (data) {
                    if (data.code==1) {
                        layer.close(index);
                        layer.msg(data.msg, {icon: 6, time: 1500}, function () {
                            table.reload(filter);
                        });
                    } else {
                        layer.msg(data.msg, {icon: 2});
						$.ajaxSetup({headers: {'X-CSRF-TOKEN': data.data.token}});
                    }
                });
            });
        },

        /**
         * 图片放大
         * @param url
         */
        showImage:function (url,w,h) {
            if (w==undefined){
                w = 'auto'
            }
            if (h==undefined){
                h = '95%'
            }
            layer.open({
                type: 1
                ,shade: false
                ,title: false
                , content: '<div style="text-align:center"><img width="100%" height="100%" src="'+url+'"></div>'
                , area: [w, h]
            });
        },

        /**
         * 图片放大
         * @param obj
         */
        showNearImage:function (obj) {
            // 浏览器窗口width height均/4 设置为图片展示的左上角坐标
            var x = document.documentElement.clientWidth/4;
            var y = document.documentElement.clientHeight/4;
            // 图片的src
            var src = obj.src;

            // 图片宽高/3 即缩放为原图片大小的1/3
            var width = obj.naturalWidth/3;
            var height = obj.naturalHeight/3;

            // 拼接img标签 设置width height src属性值
            var img_show = "<img width='" + width + "' height='" + height + "' border='0' src='" + src + "' />";
            layer.open({
                content:img_show,
                type:1,
                offset:[y+"px",x+"px"],
                title:false,
                area:['auto','auto'],
                shade:0
            });
        },

        /**
         * 防止双击按钮
         * @param select 选择器 '#id'或者'.class'
         * @param filter 是否是layui得标签
         */
       denyDoubleClick:function (select,filter){
           if (filter==true){
               select = '[lay-filter = '+select+']';
           }
           //设置禁止点击防止双击
           $(select).attr("disabled","disabled");
           clearTimeout(timer);
           var timer = setTimeout(function(){
               $(select).removeAttr("disabled");
           },1000);            //1秒之后释放防止双击
       },

        /**
         * 显示进度条
         * @param title 进度条标题
         * @param filter 精度条filter
         * @returns {*|c.index|c.index}
         */
        showProgress:function (title,filter){
            //没有传title值就不给标题
            if (title==undefined){
                title = false;
            }
            //没有传filter值默认progress
            if (filter==undefined){
                filter = 'progress';
            }
            var index = layer.open({
                type: 0,
                title: title,
                closeBtn: 0,
                btn: false,
                area: ['40%', 'auto'],
                content: '<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="'+filter+'" >' +
                            '<div class="layui-progress-bar" lay-percent="0%"></div>' +
                        '</div>'

            });
            return index;
        },

        /**
         * 设置进度条得值
         * @param percent 进度值百分比不带%符号
         * @param filter
         */
        setProgress:function (percent,filter){
            //没有传filter值默认progress
            if (filter==undefined){
                filter = 'progress';
            }
            percent = Math.round(percent);
            $('[lay-filter = '+filter+'] .layui-progress-bar').attr('lay-percent', percent +'%');
            element.progress(filter, percent +'%');
            element.render('progress',filter);
        },

        /**
         * 关闭进度条
         * @param index 进度条弹窗索引
         */
        closeProgress:function (index){
            layer.close(index);
        },

        /**
         * 上传进度条
         * @param n  进度值
         * @param index 进度条index
         * @param time 延迟时间
         */
        uploadProgress:function (n,index,time){
            if(n>=100){
                if (time==undefined){
                    this.closeProgress(index);
                }else {
					var that = this;
                    setTimeout(function () {
                        that.closeProgress(index);
                    }, time);
                }
            }else {
                this.setProgress(n);
            }
        },
		
		/**
         * 导出进度条显示函数
         * @param url 地址
         * @param field 请求参数
         * @param index 进度条index
         * @param page 当前页
         * @param limit 一次打包数据
         */
        exportProgress:function(url,field,index,page=1,limit=100,time=3000){
            var that = this;
            field['page'] = page;
            field['limit'] = limit;
            $.get(url,field,function (res) {
                if (res.code==0&&res.count>0){
                    that.setProgress(res.data.percent);
                    if (res.data.percent>=100){
                        setTimeout(function () {
                            that.closeProgress(index);
                        }, time);
                        //下载生成Excel完成的文件
                        window.location = res.data.download;
                    }else {
                        field['xls'] = res.data.path;
                        that.exportProgress(url,field,index,page+1,limit,time);
                    }
                }else {
                    layer.msg(res.msg, {icon: 2});
                }
            })
        },

        /**
         * 按照查询条件导出带进度条
         * @param url
         * @param filter
         * @param page
         * @param limit
         * @param time 延时3秒关闭
         */
        tableExport: function (url,filter,page=1,limit=100,time=3000) {
            var that = this;
            form.on('submit(' + filter + ')', function (data) {
                var index = that.showProgress('正在导出中...');
                that.exportProgress(url,data.field,index,page,limit,time);
            });
        },

    };

  //对外暴露的接口
  exports('common', obj);

});